package tmi.li.txwidgets.txwthr;

import java.util.Locale;

import tmi.li.txwidgets.TxWidgetsFinals;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class BuildService extends Service {
	public static final String TAG ="tmi.li.txwidgets.txwthr.BuildService";

	@Override
	public void onStart(Intent intent, int startId) {
		Log.d(TAG, "onStart()");
		if(intent.hasExtra("Id")) {
			Bundle extras = intent.getExtras();
			int id = extras.getInt("Id");
			buildUpdate(this, id);
			this.sendBroadcast(new Intent(TxWidgetsFinals.TXWTHR_UPDATE));
		}
		this.stopSelf();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.d(TAG, "onDestroy()");
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}


	@SuppressWarnings("static-access")
	public void buildUpdate(Context context, int id) {
		Log.d(TAG, "buildUpdate()");
		try {

			//updating the widget and appending the new infos to the old str
			//so we can save it again in the preferences
			TxWthrWidget widget = new TxWthrWidget(context);
			if(widget.load(id)) {
				WeatherUpdate updt = new WeatherUpdate();

				updt.getRss(widget._woeid, widget._format);
				//FIXME : validate updt.desc/updt.current/updt.desc2
				//alsdfjasdfaisejfasefsa 
				String lang;
				if((lang = widget._lang) != null) {
					if(lang == "null") {
						Locale local = new Locale("en");
						local = local.getDefault();
						lang = local.toString();
						widget._lang = lang;
					}
					Locale locale2 = new Locale(lang); 
					Locale.setDefault(locale2);
					Configuration config2 = new Configuration();
					config2.locale = locale2;
					// updating locale
					this.getResources().updateConfiguration(config2, null);
				}
				String desc = getDesc(updt.wcode);
				desc = desc.toUpperCase();
				if(desc.contains(";")) {
					String[] str = desc.split(";");
					updt.desc = str[0];
					updt.desc2 = str[1];
				}else {
					updt.desc = desc;
					updt.desc2= "";
				}

				widget._current = updt.current;
				widget._desc = updt.desc;
				widget._desc2 = updt.desc2;
				widget.update();
				widget.logWidget();
			}
		} catch (Exception e) {

		}   

	}
	
	public String getDesc(String wcode) {
		int _wcode = Integer.valueOf(wcode);
		wcode = Integer.toHexString(_wcode);
		String hex = "7f0600";
		if(_wcode < 16)
			return getString(Integer.parseInt(hex+"0"+wcode,16));
		return getString(Integer.parseInt(hex+wcode,16));
	}

}